package com.itheima.sfbx.insurance.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.sfbx.framework.commons.exception.ProjectException;
import com.itheima.sfbx.framework.commons.utils.BeanConv;
import com.itheima.sfbx.insurance.dto.CoefficentVO;
import com.itheima.sfbx.insurance.enums.CoefficentEnum;
import com.itheima.sfbx.insurance.mapper.CoefficentMapper;
import com.itheima.sfbx.insurance.pojo.CategoryCoefficent;
import com.itheima.sfbx.insurance.pojo.Coefficent;
import com.itheima.sfbx.insurance.service.ICategoryCoefficentService;
import com.itheima.sfbx.insurance.service.ICoefficentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
/**
 * @Description：系数项服务实现类
 */
@Slf4j
@Service
public class CoefficentServiceImpl extends ServiceImpl<CoefficentMapper, Coefficent> implements ICoefficentService {



    private LambdaQueryWrapper<Coefficent> lqw(CoefficentVO coefficentVO){
        LambdaQueryWrapper<Coefficent> queryWrapper = Wrappers.<Coefficent>lambdaQuery()
                .eq(StrUtil.isNotEmpty(coefficentVO.getCoefficentKey()),Coefficent::getCoefficentKey , coefficentVO.getCoefficentKey())
                .like(StrUtil.isNotEmpty(coefficentVO.getCoefficentKeyName()), Coefficent::getCoefficentKeyName, coefficentVO.getCoefficentKeyName())
                .eq(StrUtil.isNotEmpty(coefficentVO.getCoefficentType()), Coefficent::getCoefficentType, coefficentVO.getCoefficentType())
                .eq(StrUtil.isNotEmpty(coefficentVO.getDataState()), Coefficent::getDataState, coefficentVO.getDataState());
        return queryWrapper;
    }
    @Override
    public Page<CoefficentVO> findPage(CoefficentVO coefficentVO, int pageNum, int pageSize) {
        Page<Coefficent> page = this.page(new Page<>(pageNum, pageSize), lqw(coefficentVO));
        Page<CoefficentVO> pageVo = BeanConv.toPage(page, CoefficentVO.class);
        return pageVo;
    }

    @Override
    public CoefficentVO findById(String coefficentId) {
        Coefficent byId = this.getById(coefficentId);
        if(byId == null){
             throw new ProjectException(CoefficentEnum.FIND_ONE_FAIL);
        }
        return BeanConv.toBean(byId, CoefficentVO.class);
    }

    @Override
    @Transactional
    public CoefficentVO save(CoefficentVO coefficentVO) {
        //判断key是否存在
        Integer count = lambdaQuery().eq(Coefficent::getCoefficentKey, coefficentVO.getCoefficentKey())
                .count();
        if (count > 0) {
            log.error("key已存在");
            throw new ProjectException(CoefficentEnum.SAVE_FAIL);
        }
        //转化对象
        Coefficent bean = BeanConv.toBean(coefficentVO, Coefficent.class);
        this.save(bean);
        return BeanConv.toBean(bean, CoefficentVO.class);

    }
    @Autowired
    private ICategoryCoefficentService categoryCoefficentService;
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean update(CoefficentVO coefficentVO) {
        //判断key是否存在
        Integer count = this.lambdaQuery()
                .eq(Coefficent::getCoefficentKey, coefficentVO.getCoefficentKey())
                .ne(Coefficent::getId, coefficentVO.getId())//去掉自身
                .count();
        if (count > 0) {
            log.error("key已存在,{}", coefficentVO.getCoefficentKey());
            throw new ProjectException(CoefficentEnum.UPDATE_FAIL);
        }
        Integer count1 = categoryCoefficentService.lambdaQuery()
                .eq(CategoryCoefficent::getCoefficentKey, coefficentVO.getCoefficentKey())
                .count();
        if (count1 > 0) {
            log.error("存在关联关系,{}", coefficentVO.getCoefficentKey());
            throw new ProjectException(CoefficentEnum.UPDATE_FAIL);
        }
        //执行修改
        boolean b = updateById(BeanConv.toBean(coefficentVO, Coefficent.class));
        if (!b){
            log.error("执行修改失败,{}", coefficentVO.getCoefficentKey());
            throw new ProjectException(CoefficentEnum.UPDATE_FAIL);
        }
        return b;
    }

    @Override
    @Transactional
    public Boolean delete(String[] checkedIds) {
        List<String> list = Arrays.asList(checkedIds);
        List<Coefficent> coefficents = this.listByIds(list);
        if (CollUtil.isEmpty(coefficents)){
            log.error("不存在的id:{}",list);
            throw new ProjectException(CoefficentEnum.DEL_FAIL);
        }
        if (categoryCoefficentService.lambdaQuery()
                .in(CategoryCoefficent::getCoefficentKey,list)
                .count()>0){
            log.error("存在关联关系,{}",list);
            throw new ProjectException(CoefficentEnum.DEL_FAIL);
        }
        //删除
        boolean remove = removeByIds(list);
        if (!remove){
            log.error("删除失败,{}",list);
            throw new ProjectException(CoefficentEnum.DEL_FAIL);
        }
        return remove;
    }

    @Override
    public List<CoefficentVO> findList(CoefficentVO coefficentVO) {
        List<Coefficent> list = this.list(lqw(coefficentVO));
        return BeanConv.toBeanList(list, CoefficentVO.class);
    }

    @Override
    public CoefficentVO findByCoefficentKey(String coefficentKey) {
        Coefficent one = this.lambdaQuery().eq(Coefficent::getCoefficentKey, coefficentKey).one();
        return BeanConv.toBean(one, CoefficentVO.class);
    }
}
